<template>
    <div class="findPassword">
        <HeadBar title="找回密码"/>
        <a-form v-if="!isFindPassword"
            class="form" 
            :model="formState" 
            :label-col="labelCol" 
            :wrapper-col="wrapperCol"
            ref="formRef"
            :rules="rules"
        >
            <a-form-item v-if="!isForgetUserName" label="用户名" name="userName">
                <a-input placeholder="请输入用户名" v-model:value="formState.userName" />
            </a-form-item>
            <a-form-item v-if="!isForgetUserName || !isPhoneFill" label="手机号" name="phone">
                <a-input placeholder="请输入手机号" v-model:value="formState.phone" />
            </a-form-item>

            <a-form-item  v-if="isForgetUserName && isPhoneFill"  label="随机问题" name="question">
                <a-select 
                    v-model:value="formState.question" 
                    placeholder="请输入问题" 
                    @change="questionSelectChange"
                >
                    <a-select-option 
                        v-for="(item) in randomQuestionList" 
                        :key="item.id" 
                        :value="item.value"
                    >
                        {{item.value}}
                    </a-select-option>
                </a-select>
            </a-form-item>

             <a-form-item  v-if="isForgetUserName && isPhoneFill"  label="答案" name="answer">
                <a-input placeholder="请输入答案" v-model:value="formState.answer" />
            </a-form-item>
        </a-form>

        <div class="handleBtn" v-if="!isFindPassword">
            <div class="btn" v-if="isForgetUserName && isPhoneFill"  @click="fillPhoneNextOrPre(false)">上一步</div>
            <div class="btn" v-if="!isForgetUserName"  @click="forgetUserName">忘记用户名</div>
            <div class="btn" v-if="isForgetUserName && !isPhoneFill"   @click="forgetUserName">忘记随机问题</div>
            <div class="btn" v-if="isForgetUserName && !isPhoneFill"  @click="fillPhoneNextOrPre(true)">下一步</div>
            <div class="btn" v-if="!isForgetUserName ||isPhoneFill"  @click="findPassword">找回</div>
        </div>

        <div v-if="isFindPassword"  style="color:#727e7e;marginTop:30px">
            以下为您的密码，请妥善保存
            <h2 style="color:#e49463">{{userPassword}}</h2>
            <h4 @click="goLogin" style="color:#e49463">返回登录页</h4>
        </div>

 
    </div>     
</template>

<script setup lang="ts">
import HeadBar from '@/components/HeadBar.vue'
import { reactive, toRaw,ref } from 'vue';
import {useRouter} from 'vue-router'
import {findpasswordApi,searchUserRandomQuestionApi} from '@/api/handleUserAccount.js'

const router = useRouter()
const formState = reactive({
    userName: "",
    phone: "",
    question:"",
    answer:""
});
const formRef = ref()
const  labelCol = reactive({ span: 5 }) 
const   wrapperCol= reactive({ span: 18 })
const isForgetUserName = ref(false)


const questionId = ref('')
const userPassword = ref('')
// 密码是否已经找到
const isFindPassword = ref(false)
// 是否输入手机号
const isPhoneFill = ref(false)
// 随机问题列表
const randomQuestionList = ref([])

const questionSelectChange = (value,option)=>{
    questionId.value = option.key
}

const forgetUserName = ()=>{
    isForgetUserName.value  = !isForgetUserName.value
    // 清空表单
    formState.userName= "",
    formState.phone= "" ,
    formState.question="",
    formState.answer=""
}

// 手机号填写前/后的操作
const fillPhoneNextOrPre =(param)=>{
    if(param){
        formRef.value.validate().then(async (res)=>{
            let params = {
                phone:formState.phone
            }
            // 当前手机号下的随机问题
            let resQuestionList = await searchUserRandomQuestionApi(params)
            if(resQuestionList?.length>0){
                randomQuestionList.value = resQuestionList.map((item)=>{
                    return {
                        id:item.id,
                        value:item.question
                    }
                })
                isPhoneFill.value = param
            }
        }).catch((err)=>{
            console.log('err',err)
        })
    }else{
        isPhoneFill.value = param
    }
}

const checkPhone = (rule,value)=>{
    let regex = /^[1](([3][0-9])|([4][0,1,4-9])|([5][0-3,5-9])|([6][2,5,6,7])|([7][0-8])|([8][0-9])|([9][0-3,5-9]))[0-9]{8}$/
    if(regex.test(value)){
        return Promise.resolve()
    }else{
        return Promise.reject("请输入合法手机号")
    }
}


const rules = ref({
    userName:[
        {
            required:true,
            message:"请输入用户名",
            trigger:'blur'
        }
    ],
    phone:[
        {
            required:true,
            message:"请输入手机号",
            trigger:'blur'
        },
        {
            validator:checkPhone,
            trigger:'blur'
        }
    ],
    question:[
        {
             required:true,
            message:"请输入问题",
            trigger:'blur'
        }
    ],
    answer:[
        {
            required:true,
            message:"请输入答案",
            trigger:'blur'
        }
    ],
})

const showPassword =()=>{
    isFindPassword.value = true

}

const findPassword = () => {
    formRef.value.validate().then(async ()=>{
        if(isForgetUserName.value){
            let params = {
                phone:formState.phone,
                randomQuestion:[
                    {
                        id: questionId.value,
                        question: formState.question,
                        answer: formState.answer
                    }
                ]
            }
            let res = await findpasswordApi(params)
            if(res && res.password){
                userPassword.value = res.password
                showPassword()
            }
        // 通过用户名和手机号找回信息
        }else{
            let params = {
                userName:formState.userName,
                phone:formState.phone
            }
            let res = await findpasswordApi(params)
            if(res  && res.password){
                userPassword.value = res.password
                showPassword()
            }
        }
    }).catch((err)=>{
        console.log('err',err)
    })
};

const goLogin = () =>{
    router.push("/login")
}

</script>


<style lang="less" scoped>

.findPassword{
    padding: 15px;
    font-size: 18px;
    box-sizing: border-box; 
    min-height: calc(100vh);
    background-color:#fae7bc;

    .form{
        margin-top: 30px;
    }


     input{
        background-color: rgba(255, 255, 255,0.68);
        border: none;
        border-radius: 5px;
        outline: none;
        padding: 2px 5px;
    }

     :deep(.ant-select-selector){
        background-color: rgba(255, 255, 255,0.68);
     }

    .handleBtn{
        display: flex;
        flex-direction: row;
        justify-content: center;
        gap:10px;
        margin-top: 20px;

        .btn{
            display: inline-block;
            background-color: #708775;
            color: white;
            font-weight: bold;
            border-radius: 15px;
            padding: 5px;
            font-size: 13px;
            width: 50%;
            max-width: 200px;

            &:nth-child(1){
                background-color: #8fa794;
            }
        }
    }
}

:deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-form-item){
    .ant-form-item-label > label{
        color:#747474;
    }
}

@media (max-width: 575px) {
    :deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-row){
        justify-content: space-between;
    }

    :deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-form-item){
        margin-bottom: 10px;
    }

    :deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-form .ant-form-item .ant-form-item-label){
        flex: 1 1 0; 
         max-width: 27%;
         text-align: end;
    }

    :deep(:where(.css-dev-only-do-not-override-1p3hq3p).ant-form .ant-form-item .ant-form-item-control){
        flex: 1 1 0; 
        max-width: 70%; 
    }
}
</style>
